﻿using System.Linq;
using System.Text;
using System.Collections.Specialized;
using Newtonsoft.Json;

namespace CometDocs
{
    internal partial class Client
    {
        /// <summary>
        /// Send an email with a download invitation of a file stored in the CometDocs online store: https://www.cometdocs.com/developer/apiDocumentation#method-sendFile 
        /// </summary>
        /// <param name="token">A valid authentication token.</param>
        /// <param name="file">A file.</param>
        /// <param name="recipients">The email's list of recipients.</param>
        /// <param name="sender">The email's sender.</param>
        /// <param name="message">The email's message.</param>
        public void SendFile(AuthenticationToken token, FileInfo file, string[] recipients, string sender = null, string message = null)
        {
            string recipientsString = recipients.Aggregate((all, r) => all + "," + r);
            if (recipientsString.StartsWith(",")) recipientsString = recipientsString.Substring(1, recipientsString.Length - 1);

            NameValueCollection @params = new NameValueCollection(5);
            @params.Add("token", token.Value);
            @params.Add("id", file.ID.ToString());
            @params.Add("recipients", recipientsString);
            if (sender != null)
            {
                @params.Add("sender", sender);
            }
            if (message != null)
            {
                @params.Add("message", message);
            }

            byte[] result = webClient.UploadValues(APIRoot + "sendFile", @params);

            string json = Encoding.ASCII.GetString(result);

            Response response = JsonConvert.DeserializeObject<Response>(json);

            CheckAndThrow(response);
        }
    }
}
